package ca.eloas.judging.rest.resources;

import ca.eloas.judging.messages.SessionCreationMessage;
import ca.eloas.judging.messages.SessionMessage;
import ca.eloas.judging.model.JudgeObject;
import ca.eloas.judging.rest.repositories.JudgeRepository;
import ca.eloas.judging.rest.security.AuthenticationAuthorizationService;
import ca.eloas.judging.rest.security.AuthenticationException;
import ca.eloas.restsupport.utils.BasicResource;

import javax.inject.Inject;
import javax.mail.AuthenticationFailedException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

/**
 * @author JP
 */
@Path("/sessions")
public class SessionsResource extends BasicResource {

    @Inject
    AuthenticationAuthorizationService service;

    @Inject
    JudgeRepository judges;

    @POST
    public SessionMessage createSession(SessionCreationMessage message) {

        try {
            JudgeObject o = judges.findByEmail(message.getEmail());
            service.authenticate(o, message.getPassword());

            SessionMessage mess = createMessage(SessionMessage.class);
            mess.setEmail(message.getEmail());

            return mess;
        } catch(AuthenticationException e) {

            throw new WebApplicationException(Response.Status.FORBIDDEN);
        }
    }

}
